const router = require('koa-router')()
const mongoose = require('mongoose')
const md5 = require('MD5');
const jwt = require('jsonwebtoken')
const config = require('../config')

router.prefix('/users')

const User = mongoose.model('User')

router.post('/login',  async (ctx) =>  {
    var username = ctx.request.body.username
    var password = ctx.request.body.password
    md5Password = md5(username+password)
    await User.find({username:username,password:md5Password},'username password')
    .then(([user]) => {
        if(user){
            user = {username:user.username,password:user.password}
            console.log(user);
            var token = jwt.sign(user, config.secretKey)
            console.log(token);
            ctx.cookies.set('token',token)
        }
        ctx.body = user ? {success:true}:{success:false}
    })
    .catch(err => ctx.throw(500, err))
})

router.post('/register', async (ctx) => {
    console.log(ctx.request.body);
    var username = ctx.request.body.username
    var password = ctx.request.body.password
    var email = ctx.request.body.email
    md5Password = md5(username+password)
    await User.find({username:username})
    .then(([doc]) => {
        if (doc) {
            return false;
        }
        return true;
    })
    .then(success => {
        if (!success) {
            return null;
        }
        return User.create({
            username:username,
            email:email,
            password:md5Password
        })
    })
    .then((doc)=>{
        ctx.body = doc ? {success:true}:{success:false}
    })
    .catch(err => ctx.throw(500, err))

})

router.get('/logout', function (ctx, next) {
    ctx.cookies.set('token','');
    return ctx.redirect('/')
})

router.get('/check', async (ctx) => {
    await User.find({username:ctx.query.username})
    .then(([doc]) => ctx.body = doc?{exist:true}:{exist:false})
    .catch(err => ctx.throw(500, err))
})

module.exports = router
